﻿using SqlSugar;
using Zhao.Common.Helper;
using Zhao.IServer.Field;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;

namespace Zhao.Service.Field
{
    public class FacilityTimePriceServer : BaseService<FacilityTimePrice>, IFacilityTimePriceServer
    {
        private readonly IUnitOfWork _unitOfWork;
        public FacilityTimePriceServer(IBaseRepository<FacilityTimePrice> baseDal, IUnitOfWork unitOfWork) : base(baseDal, unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 1正常时间段  3周末或节假日价格
        /// </summary>
        /// <returns></returns>
        public async Task<List<FTimePriceDto>> GetInfos(Expressionable<FacilityTimePrice, FieldTypes> expressionable)
        {

            var data = await _Client.Queryable<FacilityTimePrice>()
                .LeftJoin<FieldTypes>((a, b) => a.FacilityType_id == b.FieldTypeID)
                .WhereIF(expressionable != null, expressionable.ToExpression())
                .Select((a, b) => new FTimePriceDto
                {
                    id = a.Id,
                    typeName = b.FieldTypeName,
                    startTime = a.StartTime,
                    endTime = a.EndTime,
                    price = a.Price,
                    IsWeekend = a.IsWeekend,
                    typeId = a.FacilityType_id
                }).ToListAsync();

            return data;
        }

        /// <summary>
        /// 添加时间区间价格
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="venueId"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddFacilityTimePriceAsync(FTimePriceDto dto, Guid venueId)
        {
            var result = new ApiResult { Success = false };

            // 2. 检查时间冲突
            bool hasConflict = await _Client.Queryable<FacilityTimePrice>()
                .Where(x => x.FacilityType_id == dto.typeId &&
                           x.IsWeekend == dto.IsWeekend &&
                           //临界区接触不算冲突
                           (x.StartTime < dto.endTime && x.EndTime > dto.startTime ||
                            dto.startTime < x.EndTime && dto.endTime > x.StartTime))
                .WhereIF(venueId != default, x => x.VenueID == venueId)
                .AnyAsync();

            if (hasConflict)
            {
                result.Message = $"该{(dto.IsWeekend ? "周末" : "平日")}时间段已存在价格设置";
                return result;
            }

            // 3. 创建实体并保存
            var entity = new FacilityTimePrice
            {
                FacilityType_id = dto.typeId,
                VenueID = venueId,
                StartTime = dto.startTime,
                EndTime = dto.endTime,
                Price = dto.price,
                IsWeekend = dto.IsWeekend
            };

            bool isSuccess = await _Client.Insertable(entity).ExecuteCommandAsync() > 0;
            if (isSuccess)
            {
                result.Success = true;
                result.Message = "添加成功";
            }
            else
            {
                result.Message = "保存数据失败";
            }

            return result;
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="venueId"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateFacilityTimePriceAsync(FTimePriceDto dto, Guid venueId)
        {
            var result = new ApiResult { Success = false };

            // 1. 检查记录是否存在
            var existing = await _Client.Queryable<FacilityTimePrice>()
                .Where(x => x.Id == dto.id && x.VenueID == venueId)
                .FirstAsync();

            if (existing == null)
            {
                result.Message = "未找到要修改的价格记录";
                return result;
            }

            // 2. 检查时间冲突（排除自身）
            bool hasConflict = await _Client.Queryable<FacilityTimePrice>()
                .Where(x => x.Id != dto.id && // 排除自身
                           x.FacilityType_id == dto.typeId &&
                           x.IsWeekend == dto.IsWeekend &&
                           (x.StartTime < dto.endTime && x.EndTime > dto.startTime ||
                            dto.startTime < x.EndTime && dto.endTime > x.StartTime))
                .WhereIF(venueId != default, x => x.VenueID == venueId)
                .AnyAsync();

            if (hasConflict)
            {
                result.Message = $"该{(dto.IsWeekend ? "周末" : "平日")}时间段存在设置冲突请核查之后在修改";
                return result;
            }

            // 3. 更新实体
            existing.FacilityType_id = dto.typeId;
            existing.StartTime = dto.startTime;
            existing.EndTime = dto.endTime;
            existing.Price = dto.price;
            existing.IsWeekend = dto.IsWeekend;

            bool isSuccess = await _Client.Updateable(existing).ExecuteCommandAsync() > 0;
            if (isSuccess)
            {
                result.Success = true;
                result.Message = "修改成功";
            }
            else
            {
                result.Message = "保存数据失败";
            }

            return result;
        }

    }
}
